<?php

namespace common\modules\admin\controllers;

use Yii;
use common\components\AccessControl;
use common\modules\admin\models\Admin;
use common\modules\admin\models\search\AdminSearch;
use common\components\Controller;
use yii\web\NotFoundHttpException;
use common\components\Common;
/**
 * AdminController implements the CRUD actions for Admin model.
 */
class AdminController extends Controller{
    public function behaviors(){
        /* return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ]; */
        return [
            'access' => [
                'class' => AccessControl::className()
            ]
        ];
    }

    public function actionModpwd()
    {
        $model  = $this->findModel(Yii::$app->user->identity->id);
        $tips   = '';
        $model->password = '';
        $model->repassword = '';
        if (Yii::$app->request->isPost) {
            $model->setScenario(Admin::SCENARIO_MODPWD);
            $model->load(Yii::$app->request->post());
            if($model->password != $model->repassword){
                $model->addError('password', '两次密码不一致');
            }
            if(stripos($model->password, $model->name) !== false){
                $model->addError('password', '密码中包含用户名');
            }
            if(!$model->hasErrors() && $model->validate()){
                $model->password = Admin::generatePassword($model->password, $model->salt);
                if($model->save(false)){
                    $tips = '密码更新成功';

                    //修改密码后强制重新登录
                    Yii::$app->session->setFlash("success", "密码更新成功,请重新登录");
                    Yii::$app->user->logout();
                    return $this->goHome();
                }
            }
        }
        return $this->render('modpwd', [
            'model' => $model,
            'tips'  => $tips
        ]);
    }

    /**
     * Lists all Admin models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new AdminSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Admin model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Admin model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Admin();
        if (Yii::$app->request->isPost) {
            $model->load(Yii::$app->request->post());
            if(stripos($model->password, $model->name) !== false){
                $model->addError('password', '密码中包含用户名');
            }
            if(!$model->hasErrors()){
                if(Common::strongPassword($model->password)){
                    $model->salt        = Common::genRand();
                    $model->password    = Admin::generatePassword($model->password, $model->salt);
                }else{
                    $model->addError('password', '密码中必须包含数字、大小写字母、特殊字符中的三种，且至少8位');
                }
            }
            if (!$model->hasErrors() && $model->save()) {
                return $this->redirect(['index']);
            }
        }
        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing Admin model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if (Yii::$app->request->isPost) {
            $model->load(Yii::$app->request->post());
            if($model->password != $model->oldAttributes['password']){
                if(stripos($model->password, $model->name) !== false){
                    $model->addError('password', '密码中包含用户名');
                }
                if(!$model->hasErrors()){
                    if(Common::strongPassword($model->password)){
                        $model->salt        = Common::genRand();
                        $model->password    = Admin::generatePassword($model->password, $model->salt);
                    }else{
                        $model->addError('password', '密码中必须包含数字、大小写字母、特殊字符中的三种，且至少8位');
                    }
                }
            }
            if (!$model->hasErrors() && $model->save()) {
                return $this->redirect(['index']);
            }
        }
        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Admin model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $model->deleted = Admin::DELETED_YES;
        if(!$model->update(false)){
            Yii::error($model->getErrors(), __METHOD__);
        }

        return $this->redirect(['index']);
    }

    /**
     * Finds the Admin model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Admin the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Admin::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
